/*
 * @Author: hongbin
 * @Date: 2022-09-07 14:27:27
 * @LastEditors: hongbin
 * @LastEditTime: 2022-09-07 15:13:02
 * @Description:酒杯
 */
import THREE from "../../";
import { sortMeshChildren, transparentModel } from "../../helper";
import { loadGltf } from "../../helper/loaderHelper";

export const roughnessParams = {
    color: 0xffffff,
    //类似透明度
    transmission: 0.5,
    opacity: 1,
    metalness: 0,
    roughness: 0.3,
    ior: 1.3,
    //透过看物体的模糊程度
    thickness: 1.4,
    specularIntensity: 1,
};

/**
 * 处理杯子的纹理和杯子外层透明壳子
 */
const handleGlassAndWrap = (
    objects: THREE.Object3D,
    withVolume: THREE.Object3D[],
    glassModel: THREE.Mesh,
    params: THREE.MeshPhysicalMaterialParameters,
    scale: number,
    position: THREE.Vector3,
    rotation?: THREE.Vector3
) => {
    //辨别杯子和壳 大的是杯子 小的是壳 壳的点比杯子少
    const children = glassModel.children as THREE.Mesh[];
    sortMeshChildren(children);

    children.forEach((mesh) => {
        mesh.position.copy(position);
        mesh.scale.set(scale, scale, scale);
        rotation && mesh.rotation.setFromVector3(rotation, "XYZ");
    });

    const [transparentWrap, glass] = children;

    transparentModel(transparentWrap);

    glass.material = new THREE.MeshPhysicalMaterial({
        side: THREE.DoubleSide,
        // specularColor: new Color("#ffffff"),
        // color: new Color(0xffa000),
        ...params,
    });

    objects.add(...children);
    //只检测壳子 减小开销
    withVolume.push(transparentWrap);
};

export const loadGlass = (objects: THREE.Object3D, withVolume: THREE.Object3D[]) => {
    loadGltf("api/glb?name=glass.glb").then((gltf) => {
        const root = gltf.scene;
        const glass1 = root.getObjectByName("glass1") as THREE.Mesh;
        const glass2 = root.getObjectByName("glass2") as THREE.Mesh;
        const glass3 = glass1.clone(true);
        //第一次“看到”杯子会卡顿一下 就杯子放在第一次就看到的位置
        if (glass1) {
            handleGlassAndWrap(
                objects,
                withVolume,
                glass1,
                roughnessParams,
                10,
                new THREE.Vector3(60, -2.4, -120),
                new THREE.Vector3(1.5, 1, -3)
            );
            handleGlassAndWrap(
                objects,
                withVolume,
                glass3,
                { ...roughnessParams, color: new THREE.Color(0x72531e), transmission: 0.7 },
                5,
                new THREE.Vector3(-42, -2.5, -97)
            );
        }
        glass2 &&
            handleGlassAndWrap(
                objects,
                withVolume,
                glass2,
                { ...roughnessParams, roughness: 0.2, transmission: 0.9 },
                10,
                new THREE.Vector3(43, -1, -64)
            );
        window.render();
    });
};
